package com.android.tnovoselec.travelassistant.overlay;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.android.tnovoselec.travelassistant.Constant;
import com.android.tnovoselec.travelassistant.R;
import com.android.tnovoselec.travelassistant.dto.BankomatDto;
import com.android.tnovoselec.travelassistant.view.CustomMapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
import com.google.android.maps.OverlayItem;
import com.nth.android.lbs.location.MyLocationService;

public class BankomatiOverlay extends ItemizedOverlay<OverlayItem> implements OnClickListener {
	public interface BankomatSelectedListener {
		public void onBankomatSelected();
	}

	private Context mContext;

	private List<BankomatDto> items;
	private List<BankomatOverlayItem> overlayItems;
	private View popupView;
	private CustomMapView mapview;

	private Drawable hpbMarker;
	private Drawable zabaMarker;
	private Drawable pbzMarker;
	private Drawable otpMarker;
	private Drawable rbaMarker;
	private Drawable splitskaMarker;
	private Drawable ersteMarker;
	private Drawable hypoMarker;

	private BankomatSelectedListener listener;

	private int lastTappedItem = -1;

	private static final Criteria CRITERIA = new Criteria();
	static {
		CRITERIA.setAccuracy(Criteria.ACCURACY_COARSE);
		CRITERIA.setAltitudeRequired(false);
		CRITERIA.setBearingRequired(false);
		CRITERIA.setCostAllowed(true);
		CRITERIA.setSpeedRequired(false);
		CRITERIA.setPowerRequirement(Criteria.NO_REQUIREMENT);
	}

	public BankomatiOverlay(Context context, Drawable defaultMarker, List<BankomatDto> items, CustomMapView mapview) {
		super(boundCenter(defaultMarker));

		this.mContext = context;

		hpbMarker = context.getResources().getDrawable(R.drawable.hpb_icon);
		zabaMarker = context.getResources().getDrawable(R.drawable.zaba_icon);
		pbzMarker = context.getResources().getDrawable(R.drawable.pbz_icon);
		otpMarker = context.getResources().getDrawable(R.drawable.otp_icon);
		rbaMarker = context.getResources().getDrawable(R.drawable.rba_icon);
		splitskaMarker = context.getResources().getDrawable(R.drawable.splitska_icon);
		ersteMarker = context.getResources().getDrawable(R.drawable.erste_icon);
		hypoMarker = context.getResources().getDrawable(R.drawable.hypo_icon);

		this.items = items;
		overlayItems = new ArrayList<BankomatOverlayItem>();
		if (items != null) {
			for (BankomatDto bankomat : items) {
				BankomatOverlayItem item = new BankomatOverlayItem(new GeoPoint((int) (bankomat.getLatitude() * 1e6), (int) (bankomat.getLongitude() * 1e6)),
						bankomat.getGrad() + " " + bankomat.getAdresa(), bankomat.getBank_id(), bankomat.getBank_id());
				item.setMarker(defaultMarker);
				overlayItems.add(item);
			}
		}

		popupView = LayoutInflater.from(context).inflate(R.layout.map_popup, null);
		popupView.setOnClickListener(this);
		this.mapview = mapview;
		populate();
	}

	@Override
	protected OverlayItem createItem(int i) {

		return overlayItems.get(i);
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		// TODO Auto-generated method stub
		super.draw(canvas, mapView, false);
	}

	@Override
	public int size() {
		return (items != null) ? items.size() : 0;
	}

	public void adjustMapViewToPOIs(CustomMapView mapView, GeoPoint geoPoint) {
		if (items.size() > 0) {
			float minLat = 90;
			float maxLat = -90;
			float minLng = 180;
			float maxLng = -180;

			for (BankomatDto item : items) {
				if (item.getLatitude() < minLat) {
					minLat = item.getLatitude();
				}
				if (item.getLatitude() > maxLat) {
					maxLat = item.getLatitude();
				}
				if (item.getLongitude() < minLng) {
					minLng = item.getLongitude();
				}
				if (item.getLongitude() > maxLng) {
					maxLng = item.getLongitude();
				}
			}
			if (geoPoint != null) {
				if (geoPoint.getLatitudeE6() < minLat * 1e6) {
					minLat = (float) (geoPoint.getLatitudeE6() / 1E6);
				}
				if (geoPoint.getLatitudeE6() > maxLat * 1e6) {
					maxLat = (float) (geoPoint.getLatitudeE6() / 1E6);
				}
				if (geoPoint.getLatitudeE6() < minLng * 1e6) {
					minLng = (float) (geoPoint.getLongitudeE6() / 1E6);
				}
				if (geoPoint.getLatitudeE6() > maxLng * 1e6) {
					maxLng = (float) (geoPoint.getLongitudeE6() / 1E6);
				}
			}

			mapView.animateTo(new GeoPoint((int) ((minLat + maxLat) / 2 * 1E6), (int) ((minLng + maxLng) / 2 * 1E6)));
			mapView.zoomToSpan((int) ((maxLat - minLat) * 1E6), (int) ((maxLng - minLng) * 1E6));
		}
	}

	@Override
	protected boolean onTap(int index) {
		lastTappedItem = index;
		final BankomatDto bankomat = items.get(index);

		final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, bankomat.getGeoPoint(), LayoutParams.BOTTOM_CENTER);

		mapview.removeAllViews();
		mapview.addView(popupView, params);

		final TextView title = (TextView) popupView.findViewById(R.id.balloon_item_title);
		title.setText(getItem(index).getTitle());

		final TextView snippet = (TextView) popupView.findViewById(R.id.balloon_item_snippet);
		snippet.setText(getItem(index).getSnippet());

		mapview.disableOnMoveListener();
		mapview.animateTo(bankomat.getGeoPoint());

		if (listener != null) {
			listener.onBankomatSelected();
		}

		return true;
	}

	public void handleListClick(BankomatDto item) {
		for (int i = 0; i < items.size(); i++) {
			if (items.get(i).getPoi_id().equals(item.getPoi_id())) {
				onTap(i);
				return;
			}
		}
	}

	@Override
	public boolean onTap(GeoPoint p, MapView mapView) {
		final boolean itemTap = super.onTap(p, mapView);
		if (!itemTap) {
			mapview.removeAllViews();
			lastTappedItem = -1;
			return true;
		}

		return itemTap;
	}

	private class BankomatOverlayItem extends OverlayItem {

		private String type;

		public BankomatOverlayItem(GeoPoint point, String title, String snippet, String type) {
			super(point, title, snippet);
			this.type = type;
		}

		@Override
		public Drawable getMarker(int stateBitset) {
			Drawable drawable = super.getMarker(stateBitset);
			if (type.toLowerCase().contains(Constant.HPB_REGEX)) {
				drawable = hpbMarker;
			} else if (type.toLowerCase().contains(Constant.PBZ_REGEX)) {
				drawable = pbzMarker;
			} else if (type.toLowerCase().contains(Constant.ZABA_REGEX)) {
				drawable = zabaMarker;
			} else if (type.toLowerCase().contains(Constant.ERSTE_REGEX)) {
				drawable = ersteMarker;
			} else if (type.toLowerCase().contains(Constant.OTP_REGEX)) {
				drawable = otpMarker;
			} else if (type.toLowerCase().contains(Constant.SPLITSKA_REGEX)) {
				drawable = splitskaMarker;
			} else if (type.toLowerCase().contains(Constant.HYPO_REGEX)) {
				drawable = hypoMarker;
			} else if (type.toLowerCase().contains(Constant.RBA_REGEX)) {
				drawable = rbaMarker;
			}
			return boundCenter(drawable);
		}

	}

	public void setListener(BankomatSelectedListener listener) {
		this.listener = listener;
	}

	@Override
	public void onClick(View v) {
		if (v == popupView) {
			GeoPoint myLoc = MyLocationService.getLastKnownGeoPoint(mContext, CRITERIA);
			float fromLat = (float) (myLoc.getLatitudeE6() / 1e6);
			float fromLng = (float) (myLoc.getLongitudeE6() / 1e6);
			float toLat = items.get(lastTappedItem).getLatitude();
			float toLng = items.get(lastTappedItem).getLongitude();
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + fromLat + "," + fromLng + "&daddr="
					+ toLat + "," + toLng + ""));
			if (mContext != null) {
				mContext.startActivity(intent);
			}
		}

	}
	
	public void hidePopup(){
		mapview.removeAllViews();
	}

}
